package com.carnation.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.service.FileService;
import com.carnation.service.impl.FileServiceImpl;
import com.carnation.utils.SessionInfo;

public class DownfileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(DownfileServlet.class);

	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		String catalogId = httpServletRequest.getParameter("catalogid");
		String fileName = httpServletRequest.getParameter("name");
		String username = null;
		SessionInfo sessionInfo = (SessionInfo)httpServletRequest.getSession().getAttribute("sessionInfo");
		if(sessionInfo == null){
			logger.info("下载文件时session失效");
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.getWriter().write("超时，请重新登录");
			httpServletResponse.getWriter().close();
			return ;
		}
		else{
			username = sessionInfo.getLoginName();
		}
		FileService fileService = new FileServiceImpl();
		File targeFile = fileService.findFileByNameAndCatalogId(fileName, catalogId);
		logger.info(fileName);
		logger.info(targeFile.getAbsolutePath());
		logger.info(targeFile.getName());
		try{
			byte[] buff = new byte[1024];
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/x-msdownload");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + new String(targeFile.getName().getBytes("UTF-8"),"ISO-8859-1") + "\"");
			ServletOutputStream out = httpServletResponse.getOutputStream();
			InputStream is = new FileInputStream(targeFile);
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(out);
			int i=-1;
			while((i=is.read(buff))!=-1){
				bos.write(buff,0,i);
			}
			is.close();
			bis.close();
			bos.flush();
			out.close();
			bos.close();
			logger.info("IP地址为" + httpServletRequest.getRemoteAddr() +"使用用户" + username + "下载了在目录" + catalogId + "下的文件:" + fileName);
		}
		catch(Exception e){
			logger.error("下载文件出错",e);
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		doPost(httpServletRequest, httpServletResponse);
	}
}
